package com.ruoyi.file.config;

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.servers.Server;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.Collections;

/**
 * 文件模块Swagger配置
 *
 * @author houyong
 */
@Configuration
public class SwaggerConfig {


    @Value("${springdoc.gatewayUrl}")
    private String gatewayUrl;

    /**
     * 文件模块Swagger API信息配置
     */
    @Bean
    public OpenAPI fileOpenAPI() {
        Server server = new Server()
                .url(gatewayUrl)
                .description("上传下载接口文档");

        return new OpenAPI()
                .addServersItem(server)
                .info(new Info()
                        .title("上传下载接口文档API")
                        .description("上传下载接口文档")
                        .version("v1.0"));
    }

    /**
     * 为CMS模块配置跨域支持，增强生产环境Swagger的兼容性
     */
    @Bean
    public CorsWebFilter cmsCorsWebFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOriginPatterns(Collections.singletonList("*"));
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.setAllowCredentials(true);
        config.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/cms/**", config);
        source.registerCorsConfiguration("/v3/api-docs/**", config);

        return new CorsWebFilter(source);
    }
}